﻿#include "form.h"
#include "ui_form.h"
#include <QDateTime>
#include <QMessageBox>

#include "result.h"


QString output_file = "log.txt";
QMutex  file_mutex;

extern bool ProductionID_flag;
extern QString ProductionID;

extern result *relt;

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);  

    QList<QSerialPortInfo> infolist;
    QList<QSerialPortInfo>::iterator iter;
    QSerialPortInfo     info;

    infolist = info.availablePorts();
    for(iter=infolist.begin(); iter != infolist.end(); iter++){
       ui->comboBox_port->addItem(iter->portName());


    }
    read_data_running = 0;
    port = new QSerialPort();
    QObject::connect(port,&QSerialPort::readyRead,this,&Form::Read_Data);
    start_flag = false;
}

Form::~Form()
{
    delete ui;
}

void Form::clean_test_status(void)
{
    qDebug()<<"clean test status";
    ui->groupBox_result->setStyleSheet(BK_YELLOW);
    QString str = QString::fromLocal8Bit("等待设备");
    ui->label_result->setText(str);

    ui->groupBox_wifi->setStyleSheet(BK_WHITE);
    ui->groupBox_rtc->setStyleSheet(BK_WHITE);
    ui->groupBox_sd->setStyleSheet(BK_WHITE);
    ui->groupBox_power->setStyleSheet(BK_WHITE);
    ui->groupBox_key->setStyleSheet(BK_WHITE);
    ui->groupBox_auth->setStyleSheet(BK_WHITE);

}

void Form::WriteResultToFile(QString result)
{
    QFile file(output_file);
    file_mutex.lock();
    if(!file.exists()){
        file.open(QIODevice::WriteOnly | QIODevice::Text);
    }else{
        file.open(QIODevice::Append | QIODevice::Text);
    }
    QTextStream str(&file);
    str << result;
    file.close();
    file_mutex.unlock();

}

void Form::start_flag_handle(QString line, int col, QGroupBox *gb)
{
    if(line.indexOf("start",0) != -1){
        gb->setStyleSheet((BK_BULE));
        qDebug()<<"Found start";
    }
    else if(line.indexOf("pass",0) != -1){
        gb->setStyleSheet(BK_GREEN);
        qDebug()<<"Found pass";

        relt->Write_result(result_line,col,"pass");
    }
    else if(line.indexOf("failed",0) != -1){
        gb->setStyleSheet(BK_RED);
        qDebug()<<"Found failed";
        relt->Write_result(result_line,col,"failed");

    }

}

void Form::write_productionID()
{
   QByteArray buf = "write_production,"+ProductionID.toUtf8()+"\n";
   qDebug()<<"command:"<<buf<<endl;
   port->write(buf);
   port->waitForBytesWritten(1000);
}


void Form::Read_Data()
{
    if(read_data_running == true){
        return;
    }
    read_data_running = true;
    QByteArray  buf;

    buf = port->readAll();
    int i;
    for(i=0;i<buf.length();i++){
        //qDebug("%02x ",buf.at(i));
        if(i%16 == 15){
            //qDebug("\r\n");
        }
    }
    //qDebug("\r\n");
    qDebug() << "Read data len:"<< buf.length()<<endl;
    QFile file("test.pcm");
    if(!file.exists()){
        file.open(QIODevice::WriteOnly | QIODevice::Text);
    }else{
        file.open(QIODevice::Append | QIODevice::Text);
    }
    //file.write(buf);
    QDataStream sfile(&file);
    sfile << buf;
    file.close();
    if(!buf.isEmpty()){
        QString str(buf);

        receive_data += str;

        //qDebug()<<receive_data;
        int start;
        start = receive_data.indexOf("%factory test%",0);
        while(start != -1){

            qDebug()<<"Found %%factory test%% :"<<start;
            int end = receive_data.indexOf("\n",start);
            if(end != -1){
                QString line = receive_data.mid(start,end-start);
                qDebug()<<line;


                int         index;

                qDebug()<<"***:"<<line;

                if(line.indexOf("auto test",0) != -1){
                    if(line.indexOf("start",0) != -1){

                        clean_test_status();
                        QString str = QString::fromLocal8Bit("测试中...");
                        ui->label_result->setText(str);
                        ui->groupBox_result->setStyleSheet(tr(BK_BULE));

                        result_line = relt->Get_line();
                        write_productionID();

                    }else if(line.indexOf("pass",0) != -1){
                        ui->groupBox_result->setStyleSheet(tr(BK_GREEN));
                        QString str = QString::fromLocal8Bit("通过");
                        ui->label_result->setText(str);
                        relt->Write_result(result_line,RESULT_RESULT_COL,"PASS");

                    }else if(line.indexOf("failed",0) != -1){
                        ui->groupBox_result->setStyleSheet(tr(BK_RED));
                        QString str = QString::fromLocal8Bit("失败");
                        ui->label_result->setText(str);
                        relt->Write_result(result_line,RESULT_RESULT_COL,"FAILED");

                    }

                }

                else if(line.indexOf("wifi",0) != -1){
                    start_flag_handle(line,RESULT_WIFI_COL,ui->groupBox_wifi);
                }
                else if(line.indexOf("sdcard",0) != -1){
                    start_flag_handle(line,RESULT_SDCARD_COL,ui->groupBox_sd);
                }
                else if(line.indexOf("rtc",0) != -1){
                    start_flag_handle(line,RESULT_RTC_COL,ui->groupBox_rtc);

                }
                else if(line.indexOf("power test",0) != -1){
                    start_flag_handle(line,RESULT_POWER_COL,ui->groupBox_power);

                }
                else if(line.indexOf("keyboard test",0) != -1){
                    start_flag_handle(line,RESULT_MANAUL_COL,ui->groupBox_key);

                }
                else if(line.indexOf("authorization ",0) != -1){
                    start_flag_handle(line,RESULT_AUTH_COL,ui->groupBox_auth);
                }

                else if(line.indexOf("udid",0) != -1){
                    index = line.indexOf(":");
                    if(index != -1){
                        QString udid = line.mid(index+1);
                        ui->lineEdit_udid->setText(udid);
                        relt->Write_result(result_line,RESULT_UDID_COL,udid);
                    }
                }
                else if(line.indexOf("mac",0) != -1){
                    index = line.indexOf(":");
                    if(index != -1){
                        QString mac = line.mid(index+1);
                        ui->lineEdit_mac->setText(mac);
                        relt->Write_result(result_line,RESULT_MAC_COL,mac);
                    }

                }
                else if(line.indexOf("appkey",0) != -1){
                    index = line.indexOf(":");
                    if(index != -1){
                        QString appkey = line.mid(index+1);
                        ui->lineEdit_appkey->setText(appkey);
                        relt->Write_result(result_line,RESULT_APPKEY_COL,appkey);
                    }

                }
                else if(line.indexOf("client name",0) != -1){
                    qDebug()<<"found client name";
                    index = line.indexOf(":");
                    if(index != -1){
                        QString appkey = line.mid(index+1);
                        ui->lineEdit_clientname->setText(appkey);
                        relt->Write_result(result_line,RESULT_CLIENTNAME_COL,appkey);
                    }

                }

                receive_data = receive_data.mid(end+1);
                start = receive_data.indexOf("%factory test%",0);
            }else{
                read_data_running = false;
                return;
            }

        }

        int point = receive_data.indexOf("\n",0);
        while(point != -1){
            qDebug()<<point<<"lengh:"<<receive_data.length();
            receive_data = receive_data.mid(point+1);
            //qDebug()<<"***"<<receive_data;
            point = receive_data.indexOf("\n",0);
        }

        //qDebug()<<receive_data;
    }
    read_data_running = false;
}

void Form::start_test(bool flag)
{
    if(flag == start_flag){
        return;
    }
    if(!flag){

        port->close();

        ui->pushButton_start->setStyleSheet(BK_GREEN);
        QString str = QString::fromLocal8Bit("开始");
        ui->pushButton_start->setText(str);
        start_flag = false;

    }else{
        QString portname = ui->comboBox_port->currentText();
        port->setPortName(portname);
        if(port->open(QIODevice::ReadWrite)){
            qDebug()<<"Open serial port "<<port->portName()<<" successful";
        }else{
            qDebug()<<"Open serial port "<<port->portName()<<" failed";
            return;
        }
        port->setBaudRate(ui->comboBox_rate->currentText().toInt());


        ui->groupBox_result->setStyleSheet(BK_YELLOW);
        QString str = QString::fromLocal8Bit("等待设备");
        ui->label_result->setText(str);
        ui->pushButton_start->setStyleSheet(BK_RED);
        str = QString::fromLocal8Bit("停止");
        ui->pushButton_start->setText(str);
        start_flag = true;
        clean_test_status();
    }
}

void Form::on_pushButton_start_clicked()
{
    qDebug()<<"on_pushButton_start"<<endl;
    if(ProductionID_flag == false){
        QString str = QString::fromLocal8Bit("请填写委工单号");
        QMessageBox::warning(this,"Warning!",str);
        return;
    }
    if(start_flag){
        start_test(false);
    }else{
        start_test(true);
    }
}

void Form::pushbutton_start(bool flag)
{

    qDebug()<<"pushbutton_start "<<start_flag<<endl;
    start_test(flag);
    qDebug()<<"pushbutton_start end"<<endl;
}
